import { isObject } from "@/utils"
import { GetanTableProps, GetanTableSorterType } from "../types"

/**
 * 支持排序
 */
export function useSorter(props: Ref<Partial<GetanTableProps>>) {
    /**
     * 默认排序
     */
    const defaultSorterRef = computed(() => unref(props).defaultSorter ?? [])
    /**
     * 选择排序
     */
    const sorterRef = ref<GetanTableSorterType>()

    const getSorterParams = (params: Recordable) => {
        const sorters = [...defaultSorterRef.value]
        if (isObject(sorterRef.value)) {
            if (sorters.findIndex(v => v.property === sorterRef.value?.property) < 0) {
                sorters.push(sorterRef.value as GetanTableSorterType)
            }
        }
        params.sorter = sorters
    }

    const setSorter = (sorter?: GetanTableSorterType) => {
        sorterRef.value = sorter
    }

    return { getSorterParams, setSorter, sorter: sorterRef }
}
